package com.daxia.ogmall.service;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.daxia.ogmall.common.AuditStatus;
import com.daxia.ogmall.common.ProfitType;
import com.daxia.ogmall.common.UserType;
import com.daxia.ogmall.dto.ProfitDTO;
import com.daxia.ogmall.dto.UserDTO;
import com.daxia.ogmall.model.City;
import com.daxia.ogmall.model.Company;
import com.daxia.ogmall.util.ValidationUtils;

@Service
public class DispatcherService {
	private static Logger logger = Logger.getLogger(DispatcherService.class);
	
	@Autowired
	private UserService userService;
	@Autowired
	private ApplicationContext applicationContext;
	@Autowired
	private ProfitService profitService;
	@Autowired
	private CompanyService companyService;
	
	/**
	 * 装修公司审核通过
	 * @param userId company对象相关联的用户
	 */
	@Transactional
	public void onCompanyActivated(Long userId) {
		if (logger.isDebugEnabled()) {
			logger.debug("onCompanyActivated...");
		}
		// find parent user (city operator)
		UserDTO sub = userService.load(userId);
		City city = sub.getCity();
		ValidationUtils.assertTrue(city != null, "装修公司所属城市为空！");
		
		UserDTO parent = userService.findCityOperatorByCity(city.getId());
		if (parent == null) {
			throw new RuntimeException("所在城市没有城市运营商");
		}
		if (parent.getType() == UserType.Manager.getValue()) {
			if (logger.isDebugEnabled()) {
				logger.debug("是欧工创建的，不产生利益");
			}
			return;
		}
		Company company = companyService.findCompanyByUserId(userId);
		if (company == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("没有找到公司");
			}
			return;
		}
		if (company.getAuditStatus() == null || company.getAuditStatus() != AuditStatus.Success.getValue()) {
			if (logger.isDebugEnabled()) {
				logger.debug("未通过审核");
			}
			return;
		}
		if (company.getCreator() == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("无法确定开通者");
				return;
			}
		}
		if (parent.getId().longValue() != company.getCreator().getId()) {
			if (logger.isDebugEnabled()) {
				logger.debug("开通人不是城市运营商自己，不产生利益");
			}
			return;
		}
		
		ProfitDTO oldP = profitService.findByTypeAndSubAccountUserId(ProfitType.AddCompany, userId);
		if (oldP != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("已经生成过profit，不再重复生成");
			}
			return;
		}
		
		// create profit
		ProfitDTO p = new ProfitDTO();
		p.setAmount(BizConfigService.profit_create_company);
		p.setRemark("开通装修公司");
		p.setSubAccountActivateUserId(company.getCreator());
		p.setSubAccountUserId(sub);
		p.setTime(new Date());
		p.setType(ProfitType.AddCompany.getValue());
		p.setUser(parent);
		profitService.create(p);
		if (logger.isDebugEnabled()) {
			logger.debug("创建了profit");
		}
		
	}
}
